import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Space,
  Modal,
  Form,
  message,
  Popconfirm,
  Card,
  Tag,
  Select,
  DatePicker
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  EyeOutlined,
  UserOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const { Option } = Select;

const TeacherList = () => {
  const [teachers, setTeachers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTeacher, setEditingTeacher] = useState(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const { isAdmin } = useAuth();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useEffect(() => {
    loadTeachers();
  }, []);

  const loadTeachers = async () => {
    try {
      setLoading(true);
      const data = await apiService.getTeachers();
      setTeachers(data);
    } catch (error) {
      message.error('加载教师列表失败');
      console.error('加载教师失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    // 实现搜索逻辑
  };

  const handleCreate = () => {
    navigate('/teachers/new');
  };

  const handleEdit = (teacher) => {
    navigate(`/teachers/${teacher.id}/edit`);
  };

  const handleDelete = async (id) => {
    try {
      await apiService.deleteTeacher(id);
      message.success('删除成功');
      loadTeachers();
    } catch (error) {
      message.error('删除失败');
      console.error('删除教师失败:', error);
    }
  };

  const handleSubmit = async (values) => {
    try {
      const teacherData = {
        ...values,
        birthDate: values.birthDate ? values.birthDate.format('YYYY-MM-DD') : null
      };

      if (editingTeacher) {
        await apiService.updateTeacher(editingTeacher.id, teacherData);
        message.success('更新成功');
      } else {
        await apiService.createTeacher(teacherData);
        message.success('创建成功');
      }

      setModalVisible(false);
      loadTeachers();
    } catch (error) {
      message.error((editingTeacher ? '更新失败' : '创建失败') + ': ' + (error.response?.data?.message || error.message));
      console.error('提交教师失败:', error);
    }
  };

  // 过滤数据
  const filteredTeachers = teachers.filter(teacher => {
    if (!searchKeyword) return true;
    
    const keyword = searchKeyword.toLowerCase();
    const name = teacher.name?.toLowerCase() || '';
    const email = teacher.email?.toLowerCase() || '';
    const department = teacher.department?.toLowerCase() || '';
    const title = teacher.title?.toLowerCase() || '';
    
    return name.includes(keyword) || 
           email.includes(keyword) ||
           department.includes(keyword) ||
           title.includes(keyword);
  });

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <UserOutlined />
          <Button
            type="link"
            onClick={() => navigate(`/teachers/${record.id}`)}
          >
            {text}
          </Button>
        </Space>
      ),
      sorter: (a, b) => a.name.localeCompare(b.name)
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80,
      render: (gender) => (
        <Tag color={gender === 'MALE' ? 'blue' : 'pink'}>
          {gender === 'MALE' ? '男' : '女'}
        </Tag>
      ),
      filters: [
        { text: '男', value: 'MALE' },
        { text: '女', value: 'FEMALE' }
      ],
      onFilter: (value, record) => record.gender === value
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      ellipsis: true
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 120
    },
    {
      title: '院系',
      dataIndex: 'department',
      key: 'department',
      ellipsis: true,
      filters: [
        { text: '计算机学院', value: '计算机学院' },
        { text: '数学学院', value: '数学学院' },
        { text: '物理学院', value: '物理学院' },
        { text: '化学学院', value: '化学学院' },
        { text: '生物学院', value: '生物学院' },
        { text: '外语学院', value: '外语学院' },
        { text: '经济学院', value: '经济学院' },
        { text: '管理学院', value: '管理学院' }
      ],
      onFilter: (value, record) => record.department === value
    },
    {
      title: '职称',
      dataIndex: 'title',
      key: 'title',
      width: 100,
      render: (title) => {
        let color = 'default';
        switch (title) {
          case '教授':
            color = 'red';
            break;
          case '副教授':
            color = 'orange';
            break;
          case '讲师':
            color = 'blue';
            break;
          case '助教':
            color = 'green';
            break;
        }
        return <Tag color={color}>{title}</Tag>;
      },
      filters: [
        { text: '教授', value: '教授' },
        { text: '副教授', value: '副教授' },
        { text: '讲师', value: '讲师' },
        { text: '助教', value: '助教' }
      ],
      onFilter: (value, record) => record.title === value
    },
    {
      title: '入职时间',
      dataIndex: 'hireDate',
      key: 'hireDate',
      width: 120,
      render: (text) => text ? moment(text).format('YYYY-MM-DD') : '-',
      sorter: (a, b) => {
        if (!a.hireDate && !b.hireDate) return 0;
        if (!a.hireDate) return 1;
        if (!b.hireDate) return -1;
        return moment(a.hireDate).unix() - moment(b.hireDate).unix();
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (text) => moment(text).format('YYYY-MM-DD'),
      sorter: (a, b) => moment(a.createdAt).unix() - moment(b.createdAt).unix()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => record && navigate(`/teachers/${record.id}`)}
          >
            查看
          </Button>
          {isAdmin() && (
            <>
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => record && handleEdit(record)}
              >
                编辑
              </Button>
              <Popconfirm
                title="确定要删除这个教师吗？"
                onConfirm={() => record && handleDelete(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="link"
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Input
              placeholder="搜索姓名、邮箱、院系或职称"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearch}
            >
              搜索
            </Button>
            {isAdmin() && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleCreate}
              >
                新建教师
              </Button>
            )}
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={filteredTeachers}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            defaultPageSize: 10,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          scroll={{ x: 1400 }}
        />
      </Card>

      <Modal
        title={editingTeacher ? '编辑教师' : '新建教师'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="gender"
            label="性别"
            rules={[{ required: true, message: '请选择性别' }]}
          >
            <Select placeholder="选择性别">
              <Option value="MALE">男</Option>
              <Option value="FEMALE">女</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="phone"
            label="电话"
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="department"
            label="院系"
            rules={[{ required: true, message: '请输入院系' }]}
          >
            <Select placeholder="选择院系" allowClear>
              <Option value="计算机学院">计算机学院</Option>
              <Option value="数学学院">数学学院</Option>
              <Option value="物理学院">物理学院</Option>
              <Option value="化学学院">化学学院</Option>
              <Option value="生物学院">生物学院</Option>
              <Option value="外语学院">外语学院</Option>
              <Option value="经济学院">经济学院</Option>
              <Option value="管理学院">管理学院</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="title"
            label="职称"
            rules={[{ required: true, message: '请选择职称' }]}
          >
            <Select placeholder="选择职称">
              <Option value="教授">教授</Option>
              <Option value="副教授">副教授</Option>
              <Option value="讲师">讲师</Option>
              <Option value="助教">助教</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="birthDate"
            label="出生日期"
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="hireDate"
            label="入职时间"
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="address"
            label="地址"
          >
            <Input.TextArea rows={2} />
          </Form.Item>

          <Form.Item
            name="bio"
            label="个人简介"
          >
            <Input.TextArea rows={3} />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingTeacher ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TeacherList;